﻿using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace QG.FrontDesk.com.ChatHubs
{
    [HubName("chatHub")]
    public class ChatHub : Hub
    {

        /// <summary>
        /// 用户的connectionID与用户名对照表
        /// </summary>
        private readonly static Dictionary<string, string> _connections = new Dictionary<string, string>();

        /// <summary>
        /// 员工上线
        /// </summary>
        /// <param name="name">名字</param>
        /// <param name="number">工号key</param>
        public void SendLogin(string number)
        {
            IHubContext chat = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();

            
            //这里便是将用户id和姓名联系起来
            if (!_connections.ContainsKey(number))
            {
                //这里便是将用户id和姓名联系起来
                _connections.Add(number, Context.ConnectionId);
            }
            else
            {
                //每次登陆id会发生变化
                _connections[number] = Context.ConnectionId;
            }
            //新用户上线，服务器广播该用户名
            //Clients.All.loginUser(userList);
            //通知用户上线
            //chat.Clients.All.senloginuser(name);
        }
        /// <summary>
        /// 发送给指定接受者
        /// </summary>
        /// <param name="sendName">发送者姓名</param>
        /// <param name="toNumber">接受者工号</param>
        /// <param name="content">发送内容</param>
        public void Echo(string sendName, string toNumber, string content)
        {
            IHubContext chat = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            //根据username获取对应的ConnectionId
            if (_connections.ContainsKey(toNumber))
            {
                var connectionId = _connections[toNumber];
                chat.Clients.Client(connectionId).send("来自【" + sendName + "】 " + content);
            }
        }
        /// <summary>
        /// 全员广播
        /// </summary>
        /// <param name="message"></param>
        public void sendmessage(string message)
        {
            IHubContext chat = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            chat.Clients.All.sendallmessage(message);


        }
        /// <summary>
        /// 除了自己广播所有人
        /// </summary>
        /// <param name="name"></param>
        /// <param name="message"></param>
        public void sendallother(string number, string message)
        {
            IHubContext chat = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            var connectionId = _connections[number];
            chat.Clients.AllExcept(connectionId).addotherMessage(message);
        }
    }
}